<?php
// api/teachers.php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }

require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$teacherID = $_GET['TeacherID'] ?? null; // Matches form/JS

switch($method) {
    case "GET":
        try {
            if ($teacherID !== null) {
                $sql = "SELECT t.*, u.Username, d.DepartmentName
                        FROM Teacher t
                        LEFT JOIN User u ON t.TeacherID = u.UserID
                        LEFT JOIN Department d ON t.DepartmentID = d.DepartmentID
                        WHERE t.TeacherID = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$teacherID]);
                $teacher = $stmt->fetch();
                if ($teacher) { echo json_encode($teacher); }
                else { http_response_code(404); echo json_encode(["error" => "Teacher not found"]); }
            } else {
                $sql = "SELECT t.*, u.Username, d.DepartmentName
                        FROM Teacher t
                        LEFT JOIN User u ON t.TeacherID = u.UserID
                        LEFT JOIN Department d ON t.DepartmentID = d.DepartmentID
                        ORDER BY t.Name ASC";
                $stmt = $pdo->query($sql);
                $teachers = $stmt->fetchAll();
                echo json_encode($teachers);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(["error" => "Failed to retrieve teacher data", "details" => $e->getMessage()]);
        }
        break;

    case "POST":
        // Create BOTH User and Teacher in a transaction
        $data = json_decode(file_get_contents("php://input"), true);

        if (!isset($data['Username'], $data['Password'], $data['Name'], $data['DepartmentID'])
            || empty(trim($data['Username'])) || empty($data['Password']) || empty(trim($data['Name'])) || empty($data['DepartmentID'])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing required fields (Username, Password, Name, DepartmentID)"]);
            exit;
        }
        // Add Title validation if needed

        $hashedPassword = password_hash($data['Password'], PASSWORD_DEFAULT);
        if ($hashedPassword === false) {
            http_response_code(500); echo json_encode(["error" => "Password hashing failed"]); exit;
        }

        $pdo->beginTransaction();
        try {
            // 1. Check duplicate username
            $stmtCheck = $pdo->prepare("SELECT UserID FROM User WHERE Username = ?");
            $stmtCheck->execute([$data['Username']]);
            if ($stmtCheck->fetch()) {
                 $pdo->rollBack();
                 http_response_code(409);
                 echo json_encode(["error" => "Username already exists"]);
                 exit;
            }

            // 2. Insert User
            $stmtUser = $pdo->prepare("INSERT INTO User (Username, Password, Role) VALUES (?, ?, 'teacher')");
            $stmtUser->execute([$data['Username'], $hashedPassword]);
            $newUserID = $pdo->lastInsertId();

            // 3. Insert Teacher
            $stmtTeacher = $pdo->prepare("INSERT INTO Teacher (TeacherID, Name, Gender, DepartmentID, Title) VALUES (?, ?, ?, ?, ?)");
            $stmtTeacher->execute([
                $newUserID, // Use UserID as TeacherID
                trim($data['Name']),
                $data['Gender'] ?? 'male',
                $data['DepartmentID'],
                !empty($data['Title']) ? trim($data['Title']) : null
            ]);

            // 4. Commit
            $pdo->commit();
            http_response_code(201);
            echo json_encode(["success" => true, "TeacherID" => $newUserID]);

        } catch (PDOException $e) {
            $pdo->rollBack();
            http_response_code(500);
             if ($e->getCode() == '23000') {
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid DepartmentID or duplicate entry)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to add teacher", "details" => $e->getMessage()]);
             }
        }
        break;

    case "PUT":
        // Update ONLY Teacher table fields
        if ($teacherID === null) {
            http_response_code(400); echo json_encode(["error" => "TeacherID is required for update"]); exit;
        }
        $data = json_decode(file_get_contents("php://input"), true);

        if (!isset($data['Name']) || empty(trim($data['Name'])) || !isset($data['DepartmentID']) || empty($data['DepartmentID'])) {
             http_response_code(400);
             echo json_encode(["error" => "Missing required fields (Name, DepartmentID) for update"]);
             exit;
         }
        // Add validation for Title, Gender

        try {
            $stmt = $pdo->prepare("UPDATE Teacher SET Name = ?, Gender = ?, DepartmentID = ?, Title = ? WHERE TeacherID = ?");
            $success = $stmt->execute([
                trim($data['Name']),
                $data['Gender'] ?? 'male',
                $data['DepartmentID'],
                !empty($data['Title']) ? trim($data['Title']) : null,
                $teacherID
            ]);
             if ($success && $stmt->rowCount() > 0) {
                 echo json_encode(["success" => true, "message" => "Teacher updated"]);
            } elseif($success) {
                 http_response_code(404);
                 echo json_encode(["error" => "Teacher not found or no changes made"]);
            } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to update teacher"]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
             if ($e->getCode() == '23000') {
                 http_response_code(400);
                 echo json_encode(["error" => "Database constraint violation (e.g., invalid DepartmentID)", "details" => $e->getMessage()]);
             } else {
                 echo json_encode(["error" => "Failed to update teacher", "details" => $e->getMessage()]);
             }
        }
        break;

    case "DELETE":
         // Delete BOTH Teacher and associated User
        if ($teacherID === null) {
            http_response_code(400); echo json_encode(["error" => "TeacherID is required for deletion"]); exit;
        }

        $pdo->beginTransaction();
        try {
             // Delete User (should cascade to Teacher based on schema)
            $stmtUser = $pdo->prepare("DELETE FROM User WHERE UserID = ?");
            $successUser = $stmtUser->execute([$teacherID]); // UserID == TeacherID

            if ($successUser && $stmtUser->rowCount() > 0) {
                 $pdo->commit();
                 echo json_encode(["success" => true, "message" => "Teacher and associated user deleted"]);
            } else {
                 $pdo->rollBack();
                 http_response_code(404);
                 echo json_encode(["error" => "Teacher (or associated User) not found"]);
            }
        } catch (PDOException $e) {
            $pdo->rollBack();
             if ($e->getCode() == '23000') { // Foreign key constraint (e.g., CourseOfferings referencing Teacher)
                 http_response_code(409);
                 echo json_encode(["error" => "Cannot delete teacher: They are assigned to existing course offerings.", "details" => $e->getMessage()]);
             } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to delete teacher", "details" => $e->getMessage()]);
             }
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
        break;
}
?>